package org.jeecg.modules.nc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.nc.entity.NcMarbasclass;
import org.jeecg.modules.nc.entity.NcMaterial;
import org.jeecg.modules.nc.entity.NcMeasdoc;
import org.jeecg.modules.nc.service.INcMarbasclassService;
import org.jeecg.modules.nc.service.INcMaterialService;
import org.jeecg.modules.nc.service.INcMeasdocService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
* @Description: NC物料表
* @Author: qixin-boot
* @Date:   2021-07-06
* @Version: V1.0
*/
// @Api(tags="NC物料表")
@RestController
@RequestMapping("/nc/ncMaterial")
@Slf4j
public class NcMaterialController extends JeecgController<NcMaterial, INcMaterialService> {
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @Autowired
   private INcMaterialService ncMaterialService;
   @Autowired
   private INcMarbasclassService marbasclassService;
   @Autowired
   private INcMeasdocService ncMeasdocService;

   /**
    * 分页列表查询
    *
    * @param ncMaterial
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @ApiOperation(value="NC物料表-分页列表查询", notes="NC物料表-分页列表查询")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(NcMaterial ncMaterial,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
       QueryWrapper<NcMaterial> queryWrapper = QueryGenerator.initQueryWrapper(ncMaterial, req.getParameterMap());
       Page<NcMaterial> page = new Page<NcMaterial>(pageNo, pageSize);
       IPage<NcMaterial> pageList = ncMaterialService.page(page, queryWrapper);
       List<NcMaterial> list = pageList.getRecords();
       for (NcMaterial entity:list) {
           if(StringUtils.isNotEmpty(entity.getPkMarbasclass())){
               NcMarbasclass ncMarbasclass = marbasclassService.getById(entity.getPkMarbasclass());
               if(ncMarbasclass!=null){
                   entity.setPkmbcName(ncMarbasclass.getName());
               }
           }
           if(StringUtils.isNotEmpty(entity.getPkMeasdoc())){
               NcMeasdoc ncMeasdoc = ncMeasdocService.getById(entity.getPkMeasdoc());
               if(ncMeasdoc!=null){
                   entity.setPkmdName(ncMeasdoc.getName());
               }
           }

       }

       return Result.OK(pageList);
   }

   /**
    *   添加
    *
    * @param ncMaterial
    * @return
    */
   @AutoLog(value = "NC物料表-添加")
   @ApiOperation(value="NC物料表-添加", notes="NC物料表-添加")
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody NcMaterial ncMaterial) {
       ncMaterialService.save(ncMaterial);
       return Result.OK("添加成功！");
   }

   /**
    *  编辑
    *
    * @param ncMaterial
    * @return
    */
   @AutoLog(value = "NC物料表-编辑")
   @ApiOperation(value="NC物料表-编辑", notes="NC物料表-编辑")
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody NcMaterial ncMaterial) {
       ncMaterialService.updateById(ncMaterial);
       return Result.OK("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "NC物料表-通过id删除")
   @ApiOperation(value="NC物料表-通过id删除", notes="NC物料表-通过id删除")
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       ncMaterialService.removeById(id);
       return Result.OK("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "NC物料表-批量删除")
   @ApiOperation(value="NC物料表-批量删除", notes="NC物料表-批量删除")
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.ncMaterialService.removeByIds(Arrays.asList(ids.split(",")));
       return Result.OK("批量删除成功!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @AutoLog(value = "NC物料表-通过id查询")
   @ApiOperation(value="NC物料表-通过id查询", notes="NC物料表-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       NcMaterial ncMaterial = ncMaterialService.getById(id);
       if(ncMaterial==null) {
           return Result.error("未找到对应数据");
       }
       return Result.OK(ncMaterial);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param ncMaterial
   */
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, NcMaterial ncMaterial) {
       // Step.1 组装查询条件
       QueryWrapper<NcMaterial> queryWrapper = QueryGenerator.initQueryWrapper(ncMaterial, request.getParameterMap());
       LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

       // Step.2 获取导出数据
       List<NcMaterial> pageList = ncMaterialService.queryList();
       List<NcMaterial> exportList = null;

       // 过滤选中数据
       String selections = request.getParameter("selections");
       if (oConvertUtils.isNotEmpty(selections)) {
           List<String> selectionList = Arrays.asList(selections.split(","));
           exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
       } else {
           exportList = pageList;
       }


       // Step.3 AutoPoi 导出Excel
       ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
       mv.addObject(NormalExcelConstants.FILE_NAME, "商品管理表"); //此处设置的filename无效 ,前端会重更新设置一下
       mv.addObject(NormalExcelConstants.CLASS, NcMaterial.class);
       //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
       ExportParams exportParams=new ExportParams("商品管理表" + "报表", "导出人:" + sysUser.getRealname(), "商品管理表");
       exportParams.setImageBasePath(upLoadPath);
       //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
       mv.addObject(NormalExcelConstants.PARAMS,exportParams);
       mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
       return mv;
//       return super.exportXls(request, ncMaterial, NcMaterial.class, "NC物料表");
   }
    /**
     * 获取对象ID
     *
     * @return
     */
    private String getId(NcMaterial item) {
        try {
            return PropertyUtils.getProperty(item, "sid").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, NcMaterial.class);
   }

}
